package com.italicatab;

import java.util.ArrayList;
import java.util.HashMap;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlSerializer;

import com.androidquery.AQuery;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ConceptProdctDetail extends Activity implements OnClickListener {
	// All static variables
	static final String URL = "http://makemyonlineshop.com/demo/italica/api/v1/product_info_from_id/";
	// XML node keys
	ProgressBar PROGRESS_BAR;
	ListView List_info;
	NetworkInfo nwinfo;
	AQuery AQ;
	ImageView IV_APP_ICON;
	// RelativeLayout RL_DRAWER, RL_TOP_DRAWER;
	TextView TV_HEADER;
	ImageView IV_PRODUCTS, IV_ABOUT_US, IV_CONTACT_US, IV_HOME, IV_PROJECTS;
	String TAG_NAME, IMG_URL;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.concept_product_detail);
		init();
		TAG_NAME = getIntent().getExtras().getString("id");
		TV_HEADER.setText(TAG_NAME);
		TAG_NAME = TAG_NAME.replace(" ", "%20");
		IMG_URL = getIntent().getExtras().getString("url");
		AQ = new AQuery(ConceptProdctDetail.this);
		AQ.id(R.id.iv_center).image(IMG_URL);
		if (isOnline()) {
			General.ProductsDetailInfo = new ArrayList<HashMap<String, String>>();
			new GetProductFromTag().execute();
		} else {
			Toast.makeText(getApplicationContext(),
					"Please Check Internet connection", Toast.LENGTH_SHORT)
					.show();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.gc();
	}

	private void init() {
		IV_PRODUCTS = (ImageView) findViewById(R.id.iv_product);
		IV_PRODUCTS.setOnClickListener(this);
		IV_ABOUT_US = (ImageView) findViewById(R.id.iv_about);
		IV_ABOUT_US.setOnClickListener(this);
		IV_CONTACT_US = (ImageView) findViewById(R.id.iv_contact);
		IV_CONTACT_US.setOnClickListener(this);
		IV_HOME = (ImageView) findViewById(R.id.iv_home);
		IV_HOME.setOnClickListener(this);
		IV_PROJECTS = (ImageView) findViewById(R.id.iv_projects);
		IV_PROJECTS.setOnClickListener(this);
		PROGRESS_BAR = (ProgressBar) findViewById(R.id.progressBar1);
		List_info = (ListView) findViewById(R.id.list_produt_detail);

		PROGRESS_BAR.setVisibility(View.GONE);

		IV_APP_ICON = (ImageView) findViewById(R.id.iv_applogo);
		IV_APP_ICON.setOnClickListener(this);

		TV_HEADER = (TextView) findViewById(R.id.tv_header);

	}

	public class GetProductFromTag extends AsyncTask<Void, Integer, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			PROGRESS_BAR.setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			XMLParser parser = new XMLParser();
			String xml = parser.getXmlFromUrl(URL + TAG_NAME); // getting
			System.out.println(xml);
			// XML

			Document doc = parser.getDomElement(xml); // getting DOM element
			doc.getDocumentElement().normalize();

			NodeList nl = doc.getElementsByTagName("product");
			// looping through all item nodes <item>
			for (int i = 0; i < nl.getLength(); i++) {
				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();
				Element e = (Element) nl.item(i);
				// adding each child node to HashMap key => value
				map.put("id_products", parser.getValue(e, "id_products"));
				map.put("productname", parser.getValue(e, "productname"));
				map.put("description", parser.getValue(e, "description"));
				map.put("categoryname", parser.getValue(e, "categoryname"));

				System.out.println(parser.getValue(e, "src"));
				map.put("src", parser.getValue(e, "src"));

				// adding HashList to ArrayList
				General.ProductsDetailInfo.add(map);
			}
			System.out.println("size is " + General.ProductsDetailInfo.size());

			// // Log.e("magnum", "product data is"+xml);
			// Document doc = parser.getDomElement(xml); // getting DOM element
			// doc.getDocumentElement().normalize();
			//
			// NodeList nl = doc.getElementsByTagName("tag");
			// // looping through all item nodes <item>
			// for (int i = 0; i < nl.getLength(); i++) {
			// // creating new HashMap
			// HashMap<String, String> map = new HashMap<String, String>();
			// Element e = (Element) nl.item(i);
			// // adding each child node to HashMap key => value
			// map.put("productfound", parser.getValue(e, "productfound"));
			// map.put("image", parser.getValue(e, "image"));
			// map.put("tag", parser.getValue(e, "tag"));
			//
			// // adding HashList to ArrayList
			// General.allTags.add(map);
			// }

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			PROGRESS_BAR.setVisibility(View.GONE);
			List_info.setAdapter(new LazyAdapterGrid(ConceptProdctDetail.this));
		}
	}

	public class LazyAdapterGrid extends BaseAdapter {
		// it is a custom adapter by this we are showing driver login
		// information as a list
		private Activity activity;
		private String[] data;
		private LayoutInflater inflater = null;

		// public ImageLoader imageLoader;

		public LazyAdapterGrid(Activity a) {
			activity = a;
			// data = d; //its image path
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// imageLoader = new ImageLoader(activity.getApplicationContext());
		}

		public int getCount() {
			return General.ProductsDetailInfo.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// View vi = convertView;
			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.raw_taged_prodect_detail, parent, false);
			}

			ImageView iv = (ImageView) convertView.findViewById(R.id.iv_one);
			TextView tv_name = (TextView) convertView
					.findViewById(R.id.tv_pro_name);
			tv_name.setText(General.ProductsDetailInfo.get(position).get(
					"productname"));
			TextView tv_count = (TextView) convertView
					.findViewById(R.id.tv_cat_name);
			tv_count.setText(General.ProductsDetailInfo.get(position).get(
					"categoryname"));
			String url = General.ProductsDetailInfo.get(position).get("src");
			System.out.println(url);
			clsLazyLoad lazy = new clsLazyLoad(ConceptProdctDetail.this, true);
			iv.setTag(url);
			lazy.DisplayImage(url, ConceptProdctDetail.this, iv);
			// AQ.id(iv).image(url);

			return convertView;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private boolean isOnline() {

		// it provides Internet information
		ConnectivityManager conmanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		nwinfo = conmanager.getActiveNetworkInfo();
		return nwinfo != null;
	}

	@Override
	public void onClick(View v) {
		if (PROGRESS_BAR.getVisibility() == View.VISIBLE) {
			return;
		}
		if (v == IV_ABOUT_US) {
			Intent i = new Intent(getApplicationContext(), AboutUs.class);
			startActivity(i);
			finish();
		} else if (v == IV_CONTACT_US) {
			Intent i = new Intent(getApplicationContext(), ContactUs.class);
			startActivity(i);
			finish();
		} else if (v == IV_HOME) {
			Intent i = new Intent(getApplicationContext(), HomeScreen.class);
			startActivity(i);
			finish();
		} else if (v == IV_PROJECTS) {
			Intent i = new Intent(getApplicationContext(), Projects.class);
			startActivity(i);
			finish();
		}

	}

}
